package com.qing.microservices.nacos.reactive.consumer.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.discovery.ReactiveDiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * @author guoqf
 * @date 2021/4/7 13:26
 */
@RestController
public class HelloController {

    @Autowired
    private ReactiveDiscoveryClient reactiveDiscoveryClient;

    @Autowired
    private DiscoveryClient discoveryClient;

    private final String serviceName = "nacos-provider";

    @GetMapping("services")
    public Flux<String> getService() {
        return reactiveDiscoveryClient.getServices();
    }

    @GetMapping("/instances")
    public Flux<String> getInstances() {

        Flux<ServiceInstance> instances = reactiveDiscoveryClient.getInstances(serviceName);
        return instances.map(instance -> "[serviceId: " + instance.getServiceId() + ", instanceId: " + instance.getInstanceId() + ", host: " + instance.getHost() + ", port: " + instance.getPort() + "]");

    }

    @GetMapping("/hello")
    public Mono<String> sayHello(@RequestParam("name") String name) {
        List<ServiceInstance> instances = discoveryClient.getInstances(serviceName);
        ServiceInstance serviceInstance = instances.stream().findAny().orElseThrow(() -> new IllegalStateException("No available instance for service[" + serviceName + "]"));
        return WebClient.create("http://" + serviceInstance.getHost() + ":" + serviceInstance.getPort()).get().uri("/echo?name=" + name).retrieve().bodyToMono(String.class);
    }
}
